package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("RuleRestController")
public class RuleRestController extends CmiEmaController {

	/**
	 * Create a new Rule entity
	 * 
	 */
	@RequestMapping(value = "/newRule", method = RequestMethod.POST)
	@ResponseBody
	public Object newRule(@RequestBody Rule rule) {
		ruleService.saveRule(rule);
		return JSONObject.parse(cmiPsonService.toJsonString(ruleDAO.findRuleByPrimaryKey(rule.getId()), 2));
	}

	@RequestMapping(value = "/restNewRule", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewRule(@RequestBody String ruleJson) {
		Rule rule = new Gson().fromJson(ruleJson, Rule.class);
		appendReferences(rule);
		ruleService.saveRule(rule);
		return JSONObject.parse(cmiPsonService.toJsonString(ruleDAO.findRuleByPrimaryKey(rule.getId()), 2));
	}

	@RequestMapping(value = "/saveRule", method = RequestMethod.PUT)
	@ResponseBody
	public Rule saveRule(@RequestBody Rule rule) {
		ruleService.saveRule(rule);
		return ruleDAO.findRuleByPrimaryKey(rule.getId());
	}

	@RequestMapping(value = "/restSaveRule", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveRule(@RequestBody String ruleJson) {
		Rule rule = new Gson().fromJson(ruleJson, Rule.class);
		appendReferences(rule);
		CmiPsonService cmiPsonService = new CmiPsonService();
		ruleService.saveRule(rule);
		return JSONObject.parse(cmiPsonService.toJsonString(ruleDAO.findRuleByPrimaryKey(rule.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteRule/{ruleId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteRule(@PathVariable Integer ruleId) {
		Rule rule = ruleDAO.findRuleByPrimaryKey(ruleId);
		ruleService.deleteRule(rule);
	}

	@RequestMapping(value = "/restConfirmDeleteRules")
	@ResponseBody
	public Object restConfirmDeleteRules(@RequestBody Set<Integer> deleteRulesIds) {
		Set<Rule> deleteRules = ruleDAO.findRulesByIds(deleteRulesIds);
		Set<Rule> referencedRules = ruleService.loadReferenceRules(deleteRules);
		deleteRules.removeAll(referencedRules);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedRules);
		jsonObject.put("deleteEntitys", deleteRules);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteRules")
	@ResponseBody
	public Object restDeleteRules(@RequestBody Set<Rule> deleteRules) {
		Iterator<Rule> iterator = deleteRules.iterator();
		while (iterator.hasNext()) {
			Rule currentRule = iterator.next();
			ruleService.deleteRule(currentRule);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listRules");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadRule/{ruleId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadRule(@PathVariable Integer ruleId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(ruleDAO.findRuleByPrimaryKey(ruleId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadRuleSite/{ruleId}/site", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadRuleSite(@PathVariable Integer ruleId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(ruleDAO.findRuleByPrimaryKey(ruleId).getSite(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadRuleRulefields/{ruleId}/rulefields/{relatedrulefieldId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadRuleRulefields(@PathVariable Integer ruleId, @PathVariable Integer relatedrulefieldId,
			@RequestBody CmiPagination cmiPagination) {
		Rulefield rulefield = rulefieldDAO.findRulefieldByPrimaryKey(relatedrulefieldId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(rulefield, 2, cmiPagination));
	}

	public void appendReferences(Rule rule) {

		Site site = rule.getSite();
		if (site != null)
			rule.setSite(siteService.findSiteByPrimaryKey(site.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Rulefield> rulefieldsForRule = new HashSet<>();
		for (Rulefield rulefield_Rule : rule.getRulefieldsForRule()) {
			rulefieldsForRule.add(rulefieldService.findRulefieldByPrimaryKey(rulefield_Rule.getId()));
		}
		rule.setRulefieldsForRule(rulefieldsForRule);
	}

	@RequestMapping(value = "/restGetRuleSite/{ruleId}/site", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetRuleSite(@PathVariable Integer ruleId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(ruleDAO.findRuleByPrimaryKey(ruleId).getSite(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetRuleRulefields/{ruleId}/rulefields", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetRuleRulefields(@PathVariable Integer ruleId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(ruleDAO.findRuleByPrimaryKey(ruleId).getRulefieldsForRule(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListRules", method = RequestMethod.GET)
	@ResponseBody
	public Object restListRules() {
		return JSONObject.parse(cmiPsonService.toJsonString(ruleService.loadRules(), 2));
	}

	@RequestMapping(value = "/restListRulesPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListRulesPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = rulePaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Rule> rules = ruleDAO.findAllRules(startResult, cmiPagination.getPaginationSize());
		String ruleString = cmiPsonService.toPsonString(rules, 2, cmiPagination);

		return JSONObject.parse(ruleString);
	}

	@RequestMapping("/ruleSelectBox")
	@ResponseBody
	public JSONObject ruleSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Site":
				entitySet = siteService.loadSitesByIdSet(searchValue);
				break;

			// 被引用键
			case "Rulefield":
				entitySet = rulefieldService.loadRulefieldsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Site":
				entitySet = siteDAO.findAllSites((pageNumber - 1) * paginationSize, paginationSize);
				count = siteService.countSites();
				break;

			// 被引用键
			case "Rulefield":
				entitySet = rulefieldDAO.findAllRulefields((pageNumber - 1) * paginationSize, paginationSize);
				count = rulefieldService.countRulefields();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Site":
				entitySet = siteDAO.findSiteByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = siteService.countSitesByName(queryword);
				break;

			// 被引用键
			case "Rulefield":
				entitySet = rulefieldDAO.findRulefieldByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = rulefieldService.countRulefieldsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
